package com.sfm.tour;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLFunctions {
	
	public ArrayList<Movie> getMovies(Context context) {
	ArrayList<Movie> items=new ArrayList<Movie>();
	Movie newMovie = null;  
	LocationData newLocation = null;
	boolean isDesc = false;
	     // XmlPullParser xpp=context.getResources().getXml(R.xml.moviedata);
	    boolean res =  false;
	  //  res = writeFile(context);
	      try {
	    	  XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
	          factory.setNamespaceAware(true);
	          XmlPullParser xpp = factory.newPullParser();
	          FileInputStream fis = context.openFileInput("moviedata.xml");
				String text = "";
				 byte[] input = new byte[fis.available()];
			     while (fis.read(input) != -1) {}
			     text += new String(input);
				fis.close();
				StringReader reader = new StringReader(text);
				xpp.setInput(reader);
	    	
			while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
			    if (xpp.getEventType()==XmlPullParser.START_TAG) {
			      
			      if (xpp.getName().equals("movie")) {
			          newMovie = new Movie(xpp.getAttributeValue(0));
			      }
			      else if(xpp.getName().equals("location")) {
		            String lat = xpp.getAttributeValue(null, "lat");
		            String lon = xpp.getAttributeValue(null, "long");
			    	newLocation = new LocationData(lat,lon);
			      }
			      else if(xpp.getName().equals("description")) {
			    	  isDesc = true;
			      }
			    	
			    } else if(xpp.getEventType()==XmlPullParser.END_TAG) {
			    	if(xpp.getName().equals("movie")) {
			    		items.add(newMovie);
			    	}
			    	else if(xpp.getName().equals("location")) {
				    	  newMovie.addLocation(newLocation);
				    } 
			    	else if(xpp.getName().equals("description")) {
				    	  isDesc = false;
				      }
			    	
			    } 
			    else if(xpp.getEventType()==XmlPullParser.TEXT) {
			      if(isDesc == true) {
			    	  newLocation.setDescription(xpp.getName());
			      }
			    }
			    
			    xpp.next();
			  }
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	      return items;
	}
	
	public ArrayList<String> getAllMovies(Context context) {
		ArrayList<String> items = new ArrayList<String>();
		boolean isMovieElement = false;
      XmlPullParser xpp=context.getResources().getXml(R.xml.movielist);
		 
	      try {
	    	   while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
			    if (xpp.getEventType()==XmlPullParser.START_TAG) {
			      
			      if (xpp.getName().equals("movie")) {
			    	  isMovieElement = true;
			      }
			      
			    	
			    } else if(xpp.getEventType()==XmlPullParser.END_TAG) {
			    	if(xpp.getName().equals("movie")) {
			    		isMovieElement = false;
			    	}
			    	
			    } 
			    else if(xpp.getEventType()==XmlPullParser.TEXT) {
			      if(isMovieElement == true) {
			    	  if(xpp.getText() != null) {
			    		  items.add(xpp.getText());
			    	  }
			      }
			    }
			    
			    xpp.next();
			  }
	    	  
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	      return items;
		
	}


	public boolean writeFile(Context context) {
		InputStream in = context.getResources().openRawResource(R.raw.moviedata);
		
		InputStreamReader inputreader = new InputStreamReader(in);
        BufferedReader buffreader = new BufferedReader(inputreader);
         String line;
         StringBuilder text = new StringBuilder();

         try {
           while (( line = buffreader.readLine()) != null) {
               text.append(line);
               
             }
           

			FileOutputStream fos = context.openFileOutput("moviedata.xml", Context.MODE_PRIVATE);
			fos.write(text.toString().getBytes("UTF-8"));
			fos.close();
       } catch (IOException e) {
           return false;
       }
		return true;

	}
	
	public boolean addMovieTag(Context c, Movie movieToAdd)  {
		try {
			//Indicates if the movie to be added is already present in the xml file
			//If yes, then the location is added to the exisiting movie tag
			//If no, then a new movie element is constructed and added to the xml file
			boolean newMovie = true;
			
			String filepath = "moviedata.xml";
			
			/*
			InputStream in = c.getResources().openRawResource(R.raw.moviedata);
			//
			
			 InputStreamReader inputreader = new InputStreamReader(in);
             BufferedReader buffreader = new BufferedReader(inputreader);
              String line;
              StringBuilder text = new StringBuilder();

              try {
                while (( line = buffreader.readLine()) != null) {
                    text.append(line);
                    text.append('\n');
                  }
            } catch (IOException e) {
                return false;
            }
              */
			
			
			FileInputStream fis = c.openFileInput("moviedata.xml");
			String text = "";
			 byte[] input = new byte[fis.available()];
		     while (fis.read(input) != -1) {}
		     text += new String(input);
		//	fis.close();
		     InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
		  
			//
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder  = docFactory.newDocumentBuilder();
			//Document doc = docBuilder.parse(text.toString());
			Document doc = docBuilder.parse(is);
			
			Node root = doc.getElementsByTagName("sf-movies").item(0);
			NodeList movieList = doc.getElementsByTagName("movie"); 
			
			//Check if there is already an element in the xml file with the same title
			for(int i=0; i< movieList.getLength(); i++) {
				Node node = movieList.item(i);
				// update staff attribute
				NamedNodeMap attr = node.getAttributes();
				Node nodeAttr = attr.getNamedItem("title");
				if(nodeAttr.getTextContent() == movieToAdd.getTitle())	{
					newMovie = false;
				}
			}
			
			if(newMovie) {
				Element e = doc.createElement("movie");
				e.setAttribute("title",movieToAdd.getTitle());
				
				Element loc = doc.createElement("location");
				loc.setAttribute("lat",Double.toString(movieToAdd.getLocations().get(0).getLatitude()));
				loc.setAttribute("long",Double.toString(movieToAdd.getLocations().get(0).getLongitude()));
				
				Element time = doc.createElement("time");
				time.appendChild(doc.createTextNode(movieToAdd.getLocations().get(0).getTime()));
				
				Element desc = doc.createElement("description");
				desc.appendChild(doc.createTextNode(movieToAdd.getLocations().get(0).getDescription()));
				
				loc.appendChild(time);
				loc.appendChild(desc);
				e.appendChild(loc);
				root.appendChild(e);
				
				
			} else {
				
			}
			
			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			//StreamResult result = new StreamResult(new File(filepath));
			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);
			
			transformer.transform(source, result);
			
			
			
			fis.close();
			
			FileOutputStream fos = c.openFileOutput("moviedata.xml", Context.MODE_PRIVATE);
			fos.write(writer.toString().getBytes("UTF-8"));
			fos.close();
			
			 
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		   } catch (TransformerException tfe) {
			tfe.printStackTrace();
		   } catch (IOException ioe) {
			ioe.printStackTrace();
		   } catch (SAXException sae) {
			sae.printStackTrace();
		   }
		
		
		return true;
	}


}